package com.vf.cloud.paas.app.master.api.project.controller;

import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.vf.cloud.paas.app.master.api.file.service.IThumbnail;
import com.vf.cloud.paas.app.master.common.domain.Project;
import com.vf.cloud.paas.app.master.common.domain.ProjectSynStatus;
import com.vf.cloud.paas.app.master.common.domain.Scene;
import com.vf.cloud.paas.app.master.common.domain.User;
import com.vf.cloud.paas.app.master.common.repository.base.Thumbnail;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.log.annotation.RLog;
import com.vf.cloud.paas.common.security.annotation.TokenRequired;
import com.vf.cloud.paas.common.util.DateUtil;
import com.vf.cloud.paas.common.util.R;
import com.vf.cloud.paas.common.util.UuidUtil;
import com.vf.cloud.paas.common.util.WebUtils;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/project")
public class ProjectController {

	@Autowired
	private IThumbnail thumbnailImpl;

	@RLog(value = "获取底板列表", type = "user")
	@TokenRequired
	@GetMapping(value = { "/pages" }, produces = "application/json; charset=utf-8")
	public R<Page<Project>> pages(HttpServletRequest request,
			@RequestParam(name = "classifyId", required = false, defaultValue = "") String classifyId,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		User user = WebUtils.getCurUser(request);
		if (user == null) {
			return R.expired();
		}

		if (StrKit.equals("admin", user.getRoleMark())) {
			String sqlExceptSelect = " from " + Project.TABLE_NAME + "  a WHERE a.classify_id='" + classifyId + "' ";
			if (!StrKit.isBlank(keywords)) {
				sqlExceptSelect += " and name like '%" + keywords + "%' ";
			}
			sqlExceptSelect += "  ORDER BY   a.modify_time desc ";
			return R.ok(Project.dao.paginate(cur, limit, "select * ", sqlExceptSelect));
		} else {
			String sqlExceptSelect = " from " + Project.TABLE_NAME
					+ "  a WHERE a.id in (select project_id from master_user_project where master_id='" + user.getId()
					+ "' ) and a.classify_id='" + classifyId + "'";
			if (!StrKit.isBlank(keywords)) {
				sqlExceptSelect += " and name like '%" + keywords + "%' ";
			}
			sqlExceptSelect += "  ORDER BY   a.modify_time desc ";
			return R.ok(Project.dao.paginate(cur, limit, "select * ", sqlExceptSelect));
		}
	}

	@TokenRequired
	@RLog(value = "保存底板", type = "user")
	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Project> save(HttpServletRequest request, MultipartFile thumbnailFile, Project project) {
		try {
			Thumbnail thumbnailEntity = null;
			if (thumbnailFile != null) {
				thumbnailEntity = new Thumbnail();
				thumbnailEntity.setSize(thumbnailFile.getSize());
				thumbnailEntity.setName(project.getName());
				thumbnailEntity.setContent(new Binary(thumbnailFile.getBytes()));
			}

			if (StrKit.notBlank(project.getId())) {
				project.setModifyUserId(request.getAttribute("currentUserId").toString());
				project.setModifyTime(DateUtil.getLocalDateTime());
				project.setStatus("-1");

				Project p = Project.dao.findById(project.getId());
				project.setVersion(p.getVersion() + 0.01);

				if (project.update()) {
					if (thumbnailEntity != null) {
						try {
							thumbnailEntity.setId(project.getId());
							thumbnailImpl.save(thumbnailEntity);
						} catch (Exception e) {
						}
					}

					return R.ok(project);
				} else {
					return R.failed();
				}
			} else {
				project.setId(UuidUtil.getUUID());
				project.setCreateUserId(request.getAttribute("currentUserId").toString());
				project.setCreateTime(DateUtil.getLocalDateTime());
				project.setStatus("-1");
				if (StrKit.isBlank(project.getClassifyId())) {
					project.setClassifyId("-1");
				}
				if (project.save()) {
					if (thumbnailEntity != null) {
						try {
							thumbnailEntity.setId(project.getId());
							thumbnailImpl.save(thumbnailEntity);
						} catch (Exception e) {
						}
					}
					return R.ok(project);
				} else {
					return R.failed();
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@TokenRequired
	@RLog(value = "发布底板", type = "user")
	@Tx
	@RequestMapping(value = "/release", method = RequestMethod.POST)
	public R<Project> release(HttpServletRequest request, @RequestBody Project asset) {
		try {
			User user = WebUtils.getCurUser(request);
			asset.setModifyUserId(user.getCreateUserId());
			asset.setModifyTime(DateUtil.getLocalDateTime());
			asset.setStatus("0");
			if (asset.update()) {
				return R.ok(asset);
			} else {
				return R.failed();
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RLog(value = "删除底板", type = "user")
	@TokenRequired
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public R<String> delete(@RequestBody Project param) {
		if (param == null) {
			return R.failed("参数必填.");
		}
		if (Project.dao.deleteById(param.getId())) {
			thumbnailImpl.deleteById(param.getId());
			Db.delete("delete from master_user_project where project_id=?", param.getId());
			Db.delete("delete from api_test_custom where project_id=?", param.getId());
			return R.ok();
		}
		return R.failed();
	}

	@RLog(value = "创建场景", type = "user")
	@TokenRequired
	@RequestMapping(value = "/scene", method = RequestMethod.POST)
	public R<String> scene(HttpServletRequest request, @RequestBody Project param) {
		Scene scene = new Scene();
		scene.setId(UuidUtil.getUUID());
		scene.setName(param.getName());
		scene.setClassifyId("-1");
		scene.setProjectId(param.getId());
		Thumbnail thumbnail = thumbnailImpl.findById(param.getId());
		scene.setId(UuidUtil.getUUID());
		scene.setCreateUserId(request.getAttribute("currentUserId").toString());
		scene.setCreateTime(DateUtil.getLocalDateTime());

		if (scene.save()) {
			if (thumbnail != null) {
				thumbnail.setId(scene.getId());
				thumbnailImpl.save(thumbnail);
			}
			return R.ok();
		}
		return R.failed();
	}

	@GetMapping(value = { "/syn" }, produces = "application/json; charset=utf-8")
	public R<List<String>> syn(@RequestParam(name = "token", required = false, defaultValue = "") String token)
			throws Exception {
		List<String> waitingForSyn = new LinkedList<String>();
		List<Project> projects = Project.dao.find("select * from " + Project.TABLE_NAME + " where status='0'");
		for (Project project : projects) {
			ProjectSynStatus projectSynStatus = ProjectSynStatus.dao.findByIds(token, project.getId());
			if (projectSynStatus != null) {
				if (projectSynStatus.getVersion() < project.getVersion()) {
					waitingForSyn.add(project.getId());
				} else {
					if (!StrKit.equals("2", projectSynStatus.getStatus())
							&& !StrKit.equals("3", projectSynStatus.getStatus())) {
						waitingForSyn.add(project.getId());
					}
				}
			} else {
				waitingForSyn.add(project.getId());
			}
		}
		return R.ok(waitingForSyn);
	}

}
